package com.kongwg.java;

import org.junit.Test;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

/**
 * @author kongwg
 * @create 2020-12-08 19:25
 */
public class JDK8DateTimeTest {

    /*
    LocalDate、LocalTime、LocalDateTime 的使用
    说明：
        1.LocalDateTime相较于LocalDate、LocalTime，使用频率要高
        2.类似于Calendar
     */
    @Test
    public void test(){
    //now()获取当前的日期时间，日期+时间
        LocalTime localTime = LocalTime.now();
        LocalDate localDate = LocalDate.now();
        LocalDateTime localDateTime = LocalDateTime.now();

        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);

        //of():设置指定年月日的时间
        LocalDateTime setDateTime = localDateTime.of(2020, 9, 8, 20, 20, 10);

        System.out.println(setDateTime);
        //getXxx()
        System.out.println(localDateTime.getDayOfMonth());
        System.out.println(localDateTime.getDayOfWeek());
        System.out.println(localDateTime.getMonth());
        System.out.println(localDateTime.getMonthValue());
        System.out.println(localDateTime.getMinute());

        //体现不可更改性
        LocalDateTime localDateTime1 = localDateTime.withDayOfMonth(10);
        System.out.println(localDateTime);
        System.out.println(localDateTime1);

        LocalDateTime localDateTime2 = localDateTime.plusMonths(1);
        System.out.println(localDateTime);
        System.out.println(localDateTime2);

        LocalDateTime localDateTime3 = localDateTime.minusDays(1);
        System.out.println(localDateTime);
        System.out.println(localDateTime3);
    }
    @Test
    public void test2(){
        //now()获取的是本初子午线时区的时间
        Instant instant = Instant.now();
        System.out.println(instant);//2020-12-08T11:50:08.055Z
        //添加时间的偏移量
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);

        long toEpochMilli = instant.toEpochMilli();
        System.out.println(toEpochMilli);

        Instant instant1 = instant.ofEpochMilli(1607428525445L);
        System.out.println(instant1);

    }

    @Test
    public void test3(){
        //自定义格式化时间
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //格式化
        String format = dateTimeFormatter.format(LocalDateTime.now());
        System.out.println(format);
        //解析
        TemporalAccessor parse = dateTimeFormatter.parse("2020-12-08 08:08:40");
        System.out.println(parse);
    }
}
